<?php

namespace app\index\controller;

use app\common\controller\HomeBase;
use think\Controller;
use think\Db;
use think\Loader;

class Index extends Controller
{
    public function index()
    {
        $id = input('id/d',0);
        $info  = Db::name('person')->find($id);
        $this->assign('info',$info);
        return $this->fetch();
    }
    /**
     * Notes:返回json
     * User: Lionel
     * DateTime: 2020/8/24 15:00
     * @param $data
     * @param string $type
     */
    public function ajaxReturn($data,$type = 'json'){
        exit(json_encode($data,JSON_UNESCAPED_UNICODE));
    }

    /**
     * Notes: 报名接口
     * User: Lionel
     * DateTime: 2020/10/12 14:19
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function sub(){
        $id = input('post.id');
        $data = input('post.');
        $mobile = input('mobile');
        $i = Db::name('person')->where(['mobile'=>$mobile])->find();

        if($i){
            $id = $i['id'];
            $data['id'] = $id;
        }
        $validate = Loader::validate('Sub');// 数据验证

        if (!$validate->scene('add')->check($data)) {
            $error = $validate->getError();
            $return_arr = ['error_code' => 1, 'error_msg' => $error, 'result' => $error];
            $this->ajaxReturn($return_arr);
        }
        $data['add_time'] = time();
        if($id){

            $data['check_time'] = 0;
            $data['warn'] = 0;
            $data['status'] = 0;
            $re = Db::name('person')->update($data);
            $pid = $id;
        }else{
            Loader::import('aip.AipFace');
            $aipface = new \AipFace(config('aiplat.AppID'), config('aiplat.APIKey'), config('aiplat.SecretKey'));
            $imgdata = base64_encode(file_get_contents($data['head_pic']));
            $img = [
                "liveness_control" => 'HIGH',
                "max_user_num"=>1,
                "match_threshold"=>80
            ];
            $res = $aipface->search($imgdata,'BASE64','mgy_1',$img);
            if($res['error_code']<1){
                $return_arr = ['error_code' => 45, 'error_msg' => '该图片已存在', ];
                $this->ajaxReturn($return_arr);
            }
            $pid = Db::name('person')->insert($data,false,true);
        }

        if($pid){

//            人脸注册
            $re = $this->addUserFace($data['head_pic'],'mgy_1',$pid,input('username'));
            if($re['error_code']<1){


                if($re['error_code']>0){

                    echo json_encode(['error_code'=>$re['error_code'],'error_msg'=>$re['error_msg']]);exit;
                }else{
                    $return_arr = ['error_code' => 0, 'error_msg' => '操作成功',  ];
                    $this->ajaxReturn($return_arr);
                }




            }else{
                Db::name('person')->delete($pid);

                $return_arr = ['error_code' => 1, 'error_msg' => '图片活体检测失败，请重新上传',   ];
                $this->ajaxReturn($return_arr);
            }

        }else{
            $this->ajaxReturn(['error_code' => 1, 'error_msg' => '添加失败',  ]);
        }

    }
    /**
     * Notes: 上传头像
     * User: Lionel
     * DateTime: 2020/10/12 9:07
     */
    public function uploads()
    {
        $file = request()->file('img');
        // 移动到框架应用根目录/public/uploads/ 目录下
        if(!$file){
            echo json_encode(['error_code'=>1,'error_msg'=>'请拍照上传']);exit;
        }
        $info = $file->validate(['size'=>6000000,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads');
        if(!$info){
            // 上传失败获取错误信息
            echo json_encode(['error_code'=>1,'error_msg'=>$file->getError()]);exit;

        }

        $url = 'public' . DS . 'uploads'.DS.$info->getSaveName();
//        $image = \think\Image::open($url);
//        $width = $image->width();
//        $height = $image->height();
//        //生成缩略图、删除原图
//        $image->thumb($width, $height,1)->save($url);
//        var_dump($url);
        Loader::import('aip.AipFace');
        $aipface = new \AipFace(config('aiplat.AppID'), config('aiplat.APIKey'), config('aiplat.SecretKey'));
//        $imgdata = base64_encode(file_get_contents(UPLOAD_PATH . 'timg.jpg'));
        $imgdata = base64_encode(file_get_contents($url));
        $img = [[
            "image" => $imgdata,
            "image_type" => "BASE64",
            "face_field" => "age,beauty,spoofing",
            "option" => "COMMON",
        ]];
        $re = $aipface->faceverify($img);
        if($re['error_code']>0){
            echo json_encode(['error_code'=>$re['error_code'],'error_msg'=>errorMsg($re['error_msg'])]);exit;
        }
        echo json_encode(['error_code'=>0,'url'=>$url]);exit;

    }

    /**
     * Notes: 人脸注册
     * User: Lionel
     * DateTime: 2020/10/12 14:19
     * @param $url
     * @param $groupId
     * @param $userId
     * @return array
     */
    public function addUserFace($url,$groupId,$userId,$name='人脸图片'){
        Loader::import('aip.AipFace');
        $aipface = new \AipFace(config('aiplat.AppID'), config('aiplat.APIKey'), config('aiplat.SecretKey'));
        $imgdata = base64_encode(file_get_contents($url));
        $opt = [
            'user_info'=>$name,
            'liveness_control'=>'HIGH',
            'action_type'=>'REPLACE',
        ];
       $re =  $aipface->addUser($imgdata,'BASE64',$groupId,$userId,$opt);
        return $re;
    }

    /**
     * Notes: 人脸识别
     * User: Lionel
     * DateTime: 2020/10/12 14:41
     * @return mixed
     */
    public function searchFace(){

        if(input('ajax')){
            $file = request()->file('img');
            // 移动到框架应用根目录/public/uploads/ 目录下
            if(!$file){
                echo json_encode(['error_code'=>1,'error_msg'=>'请拍照上传']);exit;
            }
            $info = $file->validate(['size'=>6000000,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads');
            if(!$info){
                // 上传失败获取错误信息
                echo json_encode(['error_code'=>1,'error_msg'=>$file->getError()]);exit;

            }

            $url = 'public' . DS . 'uploads'.DS.$info->getSaveName();
//        $image = \think\Image::open($url);
//        $width = $image->width();
//        $height = $image->height();
//        //生成缩略图、删除原图
//        $image->thumb($width, $height,1)->save($url);
//        var_dump($url);
            Loader::import('aip.AipFace');
            $aipface = new \AipFace(config('aiplat.AppID'), config('aiplat.APIKey'), config('aiplat.SecretKey'));
            $imgdata = base64_encode(file_get_contents($url));

            $img = [
                "liveness_control" => 'HIGH',
                "max_user_num"=>1,
                "match_threshold"=>80
            ];
            $re = $aipface->search($imgdata,'BASE64','mgy_1',$img);

//            var_dump($re);exit;
            if($re['error_code']>0){
                echo json_encode(['error_code'=>$re['error_code'],'error_msg'=>$re['error_msg']]);exit;
            }else{
                $id = $re['result']['user_list'][0]['user_id'];

                Db::name('person')->update(['id'=>$id,'check_time'=>time(),'status'=>1]);
                $info = Db::name('person')->find($id);
                echo json_encode(['error_code'=>0,'error_msg'=>$re['error_msg'],'result'=>$info]);exit;
            }

        }
        return $this->fetch('search_face');
    }

    /**
     * Notes: 根据手机号查询该用户是否已报名
     * User: Lionel
     * DateTime: 2020/10/15 9:54
     */
    public function searchUser()
    {
        if(input('ajax')){
            $mobile = input('mobile');
            if(!$mobile){
                $return_arr = ['error_code' => 1, 'error_msg' => '请填写手机号'];
                $this->ajaxReturn($return_arr);
            }
            if (!preg_match("/^1[345789]\d{9}$/", $mobile)) {
                $return_arr = ['error_code' => 1, 'error_msg' => '手机号格式不正确'];
                $this->ajaxReturn($return_arr);
            }
            $info  = Db::name('person')->where(['mobile'=>$mobile])->find();
            if($info){
                $return_arr = ['error_code' => 0, 'error_msg' => '手机号格式不正确','res'=>$info,'url'=>url('index/index',['id'=>$info['id']])];
                $this->ajaxReturn($return_arr);
            }else{
                $return_arr = ['error_code' => 1, 'error_msg' => '暂无该会员'];
                $this->ajaxReturn($return_arr);
            }

        }
        return $this->fetch('search_user');
    }

}
